package com.autonavi.yunda.yunji.core.utils;

import org.apache.commons.text.CaseUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class CamelSnakeTransfer {


    private void snakeName(Object obj) {
        if (obj instanceof Map) {
            Map<String, String> snakeNameMap = new HashMap<>();
            Map<String, Object> m = (Map<String, Object>) obj;
            m.keySet().stream()
                    .filter(n -> n.contains("_"))
                    .forEach(n -> snakeNameMap.put(n, CaseUtils.toCamelCase(n, false, '_')));
            snakeNameMap.forEach((key, value) -> m.put(value, m.remove(key)));
            m.values()
                    .forEach(this::snakeName);
        } else if (obj instanceof List) {
            ((List<?>) obj).forEach(this::snakeName);
        }
    }

    private List<Map<String, Object>> doSnakeToCamel(List<Map<String, Object>> obj) {
        snakeName(obj);
        return obj;
    }

    public static List<Map<String, Object>> transformSnakeToCamel(List<Map<String, Object>> obj) {
        CamelSnakeTransfer transfer = new CamelSnakeTransfer();
        return transfer.doSnakeToCamel(obj);
    }

}
